package com.groupbaby.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.groupbaby.ydd.common.BusinessException;
import com.groupbaby.ydd.common.ResultData;
import com.groupbaby.ydd.dto.SysPageDto;
import com.groupbaby.ydd.dto.SysUserDto;
import com.groupbaby.ydd.dto.SysUserPageDto;
import com.groupbaby.ydd.entity.SysRole;
import com.groupbaby.ydd.entity.SysUser;
import com.groupbaby.ydd.service.ISysRoleService;
import com.groupbaby.ydd.service.ISysUserService;
import com.groupbaby.ydd.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys_user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 列表
     *
     * @param loginName 登录名
     * @param status    状态
     * @param phone     电话
     * @param page      页面
     * @param limit     限制
     * @return {@link ResultData}
     */
    @GetMapping("/list")
    public ResultData list(@RequestParam("login_name") String loginName, Integer status, String phone, int page, int limit) {

        Page<SysUser> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(loginName), SysUser::getLoginName, loginName);
        wrapper.eq(StringUtils.isNotEmpty(phone), SysUser::getPhone, phone);
        wrapper.eq(status != null, SysUser::getStatus, status);
        wrapper.orderByDesc(SysUser::getUpdateDate);
        userService.page(pageInfo, wrapper);
        SysPageDto pageDto=new SysPageDto();
        pageDto.setCount(pageInfo.getTotal());//总条数
        pageDto.setTotalPages(pageInfo.getPages());//总页数
        pageDto.setPageSize(limit);//每页条数
        pageDto.setCurrentPage(page);//当前页
        List<SysUserPageDto> sysUserPageDtos=pageInfo.getRecords().stream().map(
                item ->{
                    //把SysUser对象复制到SysUserPageDto中
                    SysUserPageDto sysUserPageDto=new SysUserPageDto();
                    BeanUtils.copyProperties(item,sysUserPageDto);
                    //给roleids和rolename赋值
                    //查到role_id ["be0e2540-3c49-11ec-abdc-7ba81cf6c5ef"]
                    String roleIdInfo = item.getRoleId();
                    // ["be0e2540-3c49-11ec-abdc-7ba81cf6c5ef"],给这个格式化一下
                    //将数据库查处的role_id放如集合
                    //去掉[],\",按,切割
                    String[] roleIds = roleIdInfo.replace("[", "")
                            .replace("]", "")
                            .replace("\"", "")
                            .split(",");
                    List<String> roles = Arrays.asList(roleIds);
                    //然后格局id查询rolename放入集合中
                    //查询role_id对应的name
                    LambdaQueryWrapper<SysRole> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.in(SysRole::getId, roles);
                    List<SysRole> sysRoles = sysRoleService.list(wrapper1);
                    List<String> rolename = sysRoles.stream().map(SysRole::getName).collect(Collectors.toList());

                    sysUserPageDto.setRolename(rolename);
                    return sysUserPageDto;

                }).collect(Collectors.toList());
        //将数据封装给pagedto
        pageDto.setData(sysUserPageDtos);

        return ResultData.ok("",pageDto);

    }

    /**
     * 保存
     *
     * @param sysUserDto 系统用户dto
     * @return {@link ResultData}
     */
    @PostMapping("/add")
    public ResultData save(@RequestBody SysUserDto sysUserDto) {


        //密码加密存储
        String password = DigestUtils.md5DigestAsHex(sysUserDto.getPassword().getBytes());
        sysUserDto.setPassword(password);
        //查找roleid
        List<String> roleIds = sysUserDto.getRoleIds();
        //["1c54e003c1fc4dcd9b087ef8d48abac3", "620003c0-e96c-11eb-845c-3d5efdbaf2d4",…]
        //把前端数据集合切割合并成数据库的格式 --> ["1c54e003c1fc4dcd9b087ef8d48abac3","620003c0-e96c-11eb-845c-3d5efdbaf2d4","6f64aa20-e96c-11eb-845c-3d5efdbaf2d4"]
        String roleId = "[";
        for (int i = 0; i < roleIds.size(); i++) {
            roleId += i != roleIds.size() - 1 ? "\"" + roleIds.get(i) + "\"," : "\"" + roleIds.get(i) + "\"]";
        }

        sysUserDto.setRoleId(roleId);

        userService.save(sysUserDto);
        return ResultData.ok("",sysUserDto);

    }

    /**
     * huixan
     *
     * @param sysUser 系统用户
     * @return {@link ResultData}
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(SysUser sysUser) {

        String id=sysUser.getId();
        //根基id查询
        SysUser user = userService.getById(id);
        //把密码值为空
        user.setPassword("");

        SysUserDto sysUserDto = new SysUserDto();
        BeanUtils.copyProperties(user, sysUserDto);

        //设置roleIds符合前端要求的格式
      /*  "role_id":[
        "1c54e003c1fc4dcd9b087ef8d48abac3",
                "620003c0-e96c-11eb-845c-3d5efdbaf2d4",
                "a78b5bd0-3c49-11ec-abdc-7ba81cf6c5ef"
        ],*/
        String roleIdInfo = user.getRoleId();
        String[] roleIds = roleIdInfo.replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
        for (int i = 0; i < roleIds.length; i++) {
            roleIds[i] = roleIds[i].trim();
        }
        List<String> roles = Arrays.asList(roleIds);
        sysUserDto.setRoleIds(roles);

        return ResultData.ok("",sysUserDto);

    }
    @PostMapping("/update")
    public ResultData update(@RequestBody SysUserDto sysUserDto) {

        //修改密码

        if (StringUtils.isNotEmpty(sysUserDto.getPassword())) {
            String password = DigestUtils.md5DigestAsHex(sysUserDto.getPassword().getBytes());
            sysUserDto.setPassword(password);
        }else{
            //如果传回的密码为空,则修改密码为圆的
            SysUser user = userService.getById(sysUserDto.getId());
            sysUserDto.setPassword(user.getPassword());
        }

        //修改roleId
        if (sysUserDto.getRoleIds() != null) {
            List<String> roleIds = sysUserDto.getRoleIds();

            //使roleId符合数据库对应格式
            //["1c54e003c1fc4dcd9b087ef8d48abac3","620003c0-e96c-11eb-845c-3d5efdbaf2d4","6f64aa20-e96c-11eb-845c-3d5efdbaf2d4"]
            StringBuilder roleId = new StringBuilder("[");
            for (int i = 0; i < roleIds.size(); i++) {
                roleId.append(i != roleIds.size() - 1 ? "\"" + roleIds.get(i) + "\"," : "\"" + roleIds.get(i) + "\"]");
            }

            sysUserDto.setRoleId(roleId.toString());
        }

        userService.updateById(sysUserDto);

        return ResultData.ok("",sysUserDto);
    }


    /**
     * 删除
     *
     * @param sysUser 系统用户
     * @return {@link ResultData}
     */
    @GetMapping("/del")
    public ResultData delete(SysUser sysUser) {

        SysUser user = userService.getById(sysUser.getId());

        if ("1".equals(user.getDefaultData())) {
            throw new BusinessException("系统默认数据无法删除!");
        }

        if(user.getStatus() == 1){
            throw new BusinessException("该账户处于正常使用状态,无法删除!");
        }

        userService.removeById(sysUser.getId());
        return ResultData.ok("",sysUser);

    }

}
